// uni.setStorageSync('baseUrl', BASE_URL)
import Vue from 'vue'
import base from '@/common/config';
import vuex from '@/store';
import {router,RouterMount} from '@/router'  
const BASE_URL = base.baseUrl
let throttleBool = false
import {getOpenidApi} from '@/common/api/commonApi/commonApi.js'
export default async (params) => {
	
	if(!params.noLoading){
		// 加载中
		uni.showLoading({
		    title: '加载中'
		})
	}
  
	let defaultData ={}
	if(params.isOpenId){
		defaultData.openId = uni.getStorageSync('openId')
	}
	Object.assign(defaultData,params.data)

	let count = 0
    return new Promise(async(resolve, reject) => {
		
		// #ifdef MP-WEIXIN
		if(params.isOpenId && !defaultData.openId){
			let code = ''
			await getwxCode().then( res=>{
				code = res
			})
			await getOpenidApi({
				js_code : code
			}).then( res=>{
				defaultData.openId = res.openId 
				uni.setStorageSync('openId',res.openId )
			})
		}
		// #endif
		
		let header = {
			'Content-Type':  'application/json',
			'timestamp': Date.now()
			// 'Content-Type': 'application/x-www-form-urlencoded' ,
		}
		if(params.isToken){
			header.token = uni.getStorageSync('token')
		}
		
        uni.request({
            ...params,
            url: BASE_URL + params.url,
            method: params.method || 'POST',
            // data: params.data || {},
            data: defaultData,
            dataType: "json",
            header,
            success(res) {
				uni.hideLoading()
				if(res.data.message=='token失效，请重新登录'|| res.data.message=='token不能为空'){
					once(()=>{
						uni.showToast({
						    title: '登录失效，正在重新登录',
						    duration: 3000,
						    icon: 'none',
							success: () => {
							}
						});
						setTimeout(()=>{
							uni.reLaunch({
								url:'/pages/componentsA/bingInfo/bingInfo'
							})
						},1500)
					})()
				}else if(res.data.msg == '成功获取' || res.data.msg == 'success'|| res.data.msg =='成功返回' || res.data.code == '00'){
					return resolve(res.data)
				}else{
					reject(res.data)
					let title = res.data.message ? res.data.message : res.data.msg
					if(!title) title= '服务器错误'
					uni.showToast({
					    title,
					    duration: 3000,
					    icon: 'none',
						success: () => {
						}
					});
				}
				
            },
            fail(err) {
				uni.hideLoading()
                uni.showToast({
                    title: '服务器错误',
                    duration: 3000,
                    icon: 'none',
					success: ()=>{
							reject(err)
					}
                });
				
            },
            complete() {
               
            }
        })
    })
}

function getwxCode() {
	return new Promise((resolve, reject)=>{
		wx.login({
			success(res) {
				let code = res.code
				resolve(code)
			},
		})
	})
}

function once(fn) {
    let caller = true;
    return function() {
        if(caller) {
            caller = false
            fn.apply(this, arguments)
        }
    }
    
}
